//
//  WPMenu.m
//  01 微博
//
//  Created by zhoup on 16/5/15.
//  Copyright © 2016年 zhoup. All rights reserved.
//

#import "WPMenu.h"
#import "UIView+Frame.h"


static UIButton *_cover;

static dismissBlock _block;
@interface WPMenu()

@end

@implementation WPMenu
/**
 contentView 显示的内容
 inView 在谁的下面显示
 */
+(void)show:(UIView *)contentView withView:(UIView *)inView
{
    // 1.创建window
    UIWindow *_window  = [UIApplication sharedApplication].keyWindow;
    _window.hidden = NO;
    
    // 2.创建蒙版
    UIButton *cover = [[UIButton alloc] init];
    cover.frame = [UIScreen mainScreen].bounds;
    cover.backgroundColor = [UIColor clearColor];
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    //将蒙版添加到window上
    [_window addSubview:cover];
    _cover = cover;
    
    // 3.创建菜单
    UIImageView *menuView = [[UIImageView alloc] init];
    menuView.userInteractionEnabled = YES;
    UIImage *image = [UIImage imageNamed:@"popover_background"];
    menuView.image = image;
    // 将菜单添加到蒙版上
    [cover addSubview:menuView];
    
    
    // 4.添加内容到菜单上
    // 设置内容的X和Y值(间隙)
    [menuView addSubview:contentView];
    
    // 5.设置菜单容器的frame
    CGFloat menuViewW = CGRectGetMaxX(contentView.frame) + contentView.x;
    CGFloat menuViewH = CGRectGetMaxY(contentView.frame) + contentView.y;
    menuView.frame = CGRectMake(0, 0, menuViewW, menuViewH);
    
    // 获取需要指向控件的frame, 并且是转换为和蒙版同一个坐标系的frame
    // 将fromView.frame的坐标系 从 fromView.superview  转换为 _window
    
    CGRect resultFrame = [_window convertRect:inView.frame fromView:inView.superview];
    
    // 设置菜单的Y的值
    menuView.y = CGRectGetMaxY(resultFrame);
    menuView.centerX = resultFrame.origin.x + (resultFrame.size.width * 0.5);
    
    
}

+(void)coverClick:(UIButton *)view
{
    [_cover removeFromSuperview];
     if (_block != nil) {
         _block();
         _block = nil;
     }
}

+(void)show:(UIView *)contentView withView:(UIView *)inView dismiss:(dismissBlock)dismiss
{
   _block = [dismiss copy];
    [self show:contentView withView:inView];
    
}
@end
